<?php
namespace App\Http\Logic;

use App\Models\SwtTradeAddress;
use App\Models\SwtUserAccount;
use App\Models\SwtUserWallet;
use App\Models\SwtUserWalletAddress;
use App\Models\User;
use App\Services\MakeCoinInfoService;
use App\Services\WebThreeService;
use Illuminate\Support\Facades\DB;

class AccountLogic extends BaseLogic
{
    /**
     * @notes 创建钱包账户
     * @param int $user_id
     * @param array $params
     * @return bool|array
     * @author Evil丿
     * @date 2025/03/19 16:15
     */
    public static function createAccount(int $user_id) : bool
    {
        $user_account_data = [
            "user_id"        => $user_id,
        ];

        $user_account_info = SwtUserAccount::create($user_account_data);

        if (!$user_account_info) {
            self::$error = __('account.create_fail');
            return false;
        }

        $res = MakeCoinInfoService::generateMnemonic($user_account_info -> id);

        if(!$res['success']) {
            self::$error = __('account.mnemonic_fail');
            return false;
        }

        $res = MakeCoinInfoService::generateAddress($user_account_info -> id);

        if(!$res['success']) {
            self::$error = __('account.address_fail');
            return false;
        }

        $wallet_id = SwtUserWallet::where('account_id', $user_account_info -> id) -> where('wallet_sn', 0) -> value('id');

        if(!$wallet_id) {
            self::$error = __('account.wallet_no_found');
            return false;
        }

        $addresses = SwtUserWalletAddress::where('wallet_id', $wallet_id) -> get();

        if(!$addresses) {
            self::$error = __('account.wallet_no_found');
            return false;
        }

        $addresses = $addresses -> toArray();

        $addr = [];

        foreach($addresses as $address)
        {
            if($address['chain_index'] == 99999999) {
                continue;
            }

            $addr[] = [
                "chainIndex" => $address['chain_index'],
                "address"    => $address['address']
            ];
        }

        $res = WebThreeService::createWalletAccount($addr);

        if($res['code'] != 0) {
            self::$error = $res['msg'];
            return false;
        }

        $res = SwtUserAccount::where('id', $user_account_info -> id) -> update(['okx_account_id'=> $res['data'][0]['accountId']]);

        if(!$res) {
            self::$error = __('account.edit_fail');
            return false;
        }

        return true;

    }
    /**
     * @notes 查询账户信息
     * @param int $user_id
     * @return array|bool
     * @author Evil丿
     * @date 2025/04/09 15:34
     */
    public static function queryAccount(int $user_id) : array|bool
    {
        // 判断查询结果是否为空
        $account_info = SwtUserAccount::with('wallets')->where('user_id', $user_id)->get();

        if ($account_info->isEmpty()) {
            self::$error = __('account.not_found');
            return false;
        }

        return $account_info->toArray();
    }
    /**
     * @notes 增加钱包
     * @param int $user_id
     * @param array $params
     * @return bool
     * @author Evil丿
     * @date 2025/03/19 16:15
     */
    public static function addWallet(int $user_id) : bool
    {
        $user_account_info = SwtUserAccount::firstWhere('user_id', $user_id);

        $res = MakeCoinInfoService::generateAddress($user_account_info -> id);

        if(!$res['success']) {
            self::$error = __('account.address_fail');
            return false;
        }

        $wallet_info = SwtUserWallet::where('account_id', $user_account_info -> id) -> orderBy('wallet_sn', 'desc') -> first();

        if(!$wallet_info) {
            self::$error = __('account.wallet_no_found');
            return false;
        }

        $addresses = SwtUserWalletAddress::where('wallet_id', $wallet_info -> id) -> get();

        if(!$addresses) {
            self::$error = __('account.wallet_no_found');
            return false;
        }

        $addresses = $addresses -> toArray();

        $addr = [];

        foreach($addresses as $address)
        {
            if($address['chain_index'] == 99999999) {
                continue;
            }

            $addr[] = [
                "chainIndex" => $address['chain_index'],
                "address"    => $address['address']
            ];
        }

        $params = [
            "accountId"  => $user_account_info -> okx_account_id,
            "updateType" => "add",
            "addresses"  => $addr
        ];

        $res = WebThreeService::updateWalletAccount($params);

        if($res['code'] != 0) {
            self::$error = $res['msg'];
            return false;
        }

        return true;
    }
    /**
     * @notes 删除钱包
     * @param string $wallet_id
     * @return bool
     * @author Evil丿
     * @date 2025/04/09 15:44
     */
    public static function deleteWallet(string $user_id, string $wallet_id) : bool
    {
        DB::beginTransaction();

        try {
            $user_account_info = SwtUserAccount::where('user_id', $user_id) -> first();

            if (!$user_account_info) {
                self::$error = __('account.not_found');
                return false;
            }

            $user_wallet_info = SwtUserWallet::where('id', $wallet_id) -> first();

            if (!$user_wallet_info) {
                self::$error = __('account.wallet_no_found');
                return false;
            }

            $lists = SwtUserWalletAddress::where('wallet_id', $user_wallet_info -> id) -> get();

            $addresses = $lists -> toArray();

            $addr = [];

            foreach($addresses as $address)
            {
                if($address['chain_index'] == 99999999) {
                    continue;
                }

                $addr[] = [
                    "chainIndex" => $address['chain_index'],
                    "address"    => $address['address']
                ];
            }

            $params = [
                "accountId"  => $user_account_info -> okx_account_id,
                "updateType" => "delete",
                "addresses"  => $addr
            ];

            $res = SwtUserWalletAddress::where('wallet_id', $user_wallet_info -> id) -> delete();

            if(!$res) {
                throw new \Exception(__('account.address_delete_fail'));
            }

            $res = $user_wallet_info -> delete();

            if(!$res) {
                throw new \Exception(__('account.wallet_delete_fail'));
            }

            $res = WebThreeService::updateWalletAccount($params);

            if($res['code'] != 0) {
                throw new \Exception($res['msg']);
            }

            DB::commit();
            return true;
        } catch (\Exception $e) {
            DB::rollBack();
            self::$error = $e -> getMessage();
            return false;
        }
    }
    /**
     * @notes 获取钱包下地址
     * @param array $params
     * @return array|bool
     * @author Evil丿
     * @date 2025/04/09 17:04
     */
    public static function queryWalletAddress(array $params) : array|bool
    {
        $addresses = SwtUserWalletAddress::with('chain') -> where('wallet_id', $params['walletId']) -> get();

        if ($addresses->isEmpty()) {
            self::$error = __('account.wallet_no_found');
            return false;
        }

        return $addresses->toArray();
    }
    /**
     * @notes 增加SWT
     * @param string $address
     * @param float $total
     * @return bool
     * @author Evil丿
     * @date 2025/04/09 17:07
     */
    public static function addSwt(string $user_id, float $total) : bool
    {
        $user_info =User::where('shop_user_id', $user_id) -> first();

        if(!$user_info) {
            self::$error = "未找到注册用户";
            return false;
        }

        $res = SwtTradeAddress::whereHas('trade_account', function ($query) {
                    $query->where('type', '1');
            })
            -> where('user_id', $user_info -> id)
            -> first();

        if(!$res) {
            self::$error =  __('account.address_not_found');
            return false;
        }

        $res -> total += $total;

        $res -> save();

        TradeLogLogic::create( $res -> id, $res -> trade_account -> user_id, 3, '{outside_add}' .$total.' SWT', 0, $total);

        return true;
    }

    /**
     * @notes 查询账户总资产
     * @param int $user_id
     * @return bool|array
     * @author Evil丿
     * @date 2025/04/11 11:09
     */
    public static function queryAccountBalance(int $user_id) : bool|string
    {
        $account_info = SwtUserAccount::where('user_id', $user_id) -> first();

        $info = WebThreeService::getAllBalances($account_info -> okx_account_id);

        if($info['code'] != 0) {
            self::$error = $info['msg'];
            return false;
        }

        $wallet_ids = SwtUserWallet::where('account_id', $account_info -> id) -> pluck('id');

        $total = SwtUserWalletAddress::whereIn('wallet_id', $wallet_ids) -> where('chain_index', 99999999) -> sum('total');

        $rate = WebThreeService::getRate();

        return round($total / $rate + $info['data'][0]['totalValue'], 2);
    }
}
